//
//  OAuthViewController.swift
//  weibo
//
//  Created by yellow on 15/10/16.
//  Copyright © 2015年 yellow. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {
    
    //控制器的业务逻辑都可以调用viewModel中个公开API
    var viewModel = UserAccountViewModel.sharedViewModel
    
       //登录界面需要访问微博授权的网页，所以使用UIWebView控件展示
    private lazy var webView:UIWebView? = {
        let view = UIWebView(frame: UIScreen.mainScreen().bounds)
        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        bulidWeiboLoginPage()
    }
    
    // MARK: 懒加载
    
}

// MARK: - 微博登录设置页面
extension OAuthViewController{
    
    
    
    //返回按钮事件
    @objc private func backBtnClick(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //自动填充账号密码
    @objc private func autoLoginBtnClick(){
        let js = "document.getElementById('userId').value='269419380@qq.com';"
               +
                 "document.getElementById('passwd').value ='hzc15825928453';"
//        let js = "document.getElementById('userId').value = 'daoge10000@sina.cn';" +
//        "document.getElementById('passwd').value = 'qqq123';"
        
        webView!.stringByEvaluatingJavaScriptFromString(js)
    }
    
    private func bulidWeiboLoginPage(){
        title = "微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "backBtnClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动登录", style: .Plain, target: self, action: "autoLoginBtnClick")
        //以上为导航栏设置
        view = webView!
        
        //以下为设置webView显示的网页
        let weiboManager = WeiboAPIManager.manager
        let request = NSURLRequest(URL: weiboManager.authorizeURL)
        webView?.loadRequest(request)
        webView?.delegate = self
    }
}

// MARK: - UIWebViewDelegate 获取code，并拦截授权回调页：http://www.baidu.com，弹出view让用户分享使用该app的微博
extension OAuthViewController:UIWebViewDelegate{
    
/// 关闭SVProgressHUD的view
    private func closeHUD(){
        SVProgressHUD.dismiss()
        self.dismissViewControllerAnimated(true, completion: nil)
    }

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let requestURLString = request.URL?.host where requestURLString.containsString("baidu") == true else{
            return true
        }
        
        guard let url = request.URL?.query where url.containsString("code=") == true else{
            

            delayDo(1, call: { () -> () in
                self.closeHUD()
            })
            print("授权失败")
            return false
        }
        
        //拿到code后，换取用户token，将token存储在沙盒
        let code = url.substringFromIndex("code=".endIndex)
        

        viewModel.getAccessTokenByCode(code) { (isSuccess) -> () in
            if isSuccess {
                print("获取用户信息成功")
                // dismissViewControllerAnimated 方法不会立即将控制器销毁，如果在闭包外执行将无法释放以前的MainViewController
                self.dismissViewControllerAnimated(true, completion: { () -> Void in
                    // 通知中心是同步的 - 一旦发送通知，会先执行监听方法，直接结束后，才执行后续代码
                    NSNotificationCenter.defaultCenter().postNotificationName(jump2MainVCNotification, object: "MainViewController")
                })
            
                
            }else{
                SVProgressHUD.showWithStatus("网络出现了问题")
                delayDo(1, call: { () -> () in
                    SVProgressHUD.dismiss()
                    self.dismissViewControllerAnimated(true, completion: nil)
                })
                print("获取用户信息成功出错了")
            }
        }
        return false
    }
    
    
    //每执行一次网络请求，在开始时显示转圈
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    //完成网络请求关闭转圈
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}
